<?php


namespace app\v1_0\controller\company;


use app\common\logic\StaffLogic;
use app\common\logic\StaffParseLogic;
use app\common\model\CompanyStaffManage;
use app\common\model\Member;
use think\Db;
use think\Exception;

class StaffManage extends \app\v1_0\controller\common\Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->checkLogin(1);
        $this->interceptCompanyProfile();
    }

    public function index(){
        $current_page = input('page/d', 1, 'intval');
        $pagesize = input('pagesize/d', 10, 'intval');
        $status = input('status/a');

        $where=['com_id'=> $this->company_profile->id];

//        $filterCompany=input('get.filterCompany/a', []);
        $filterDepartment=input('get.filterDepartment/a', []);
        $status_func = function ($q)use($status){
            switch ($status['field']){
                case 'total':
                    $q->where('leave_post','NULL');
                    break;
                case 'leave_post':
                    $q->where('leave_post','是');
                    break;
                default:
                    $q->where($status['field'],$status['value']);
                    $q->where('leave_post','NULL');
            }
        };
        $query = model('CompanyStaffManage')
            ->field('*')
            ->where($where)
            ->when($status,$status_func)
            ->page($current_page, $pagesize);
//        if(!empty($filterCompany)){
//            $query->where(['coms_id'=>['like',  implode(',',$filterCompany) . '%']]);
//        }
        if(!empty($filterDepartment)){
            $query->where(['coms_d_id'=>['like',  implode(',',$filterDepartment) . '%']]);
        }

        $list = $query->order('id desc')->select();
        foreach ($list as $value){
            $value['entry_status'] || $value['entry_status'] = '正式员工';
        }
        $return['total'] = model('CompanyStaffManage')->where($where)->when($status,$status_func)
            ->count();

        $statistics = model('CompanyStaffManage')->where($where)
            ->field('leave_post,job_nature,entry_status,entry_status,transfer,promotion,demotion,stand_down')
            ->select();
        $return['statistics']['total']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是';
        })->count();//现有员工
        $return['statistics']['full_time']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['job_nature'] == '全职';
        })->count();//全职
        $return['statistics']['part_time']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['job_nature'] == '兼职';
        })->count();//兼职
        $return['statistics']['intern']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['entry_status'] == '实习生';
        })->count();//实习生
        $return['statistics']['trial_period']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['entry_status'] == '试用期';
        })->count();//试用期
        $return['statistics']['later_officially']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['entry_status'] == '待转正';
        })->count();//待转正
        $return['statistics']['transfer']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['transfer'] == '是';
        })->count();//调岗
        $return['statistics']['promotion']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['promotion'] == '是';
        })->count();//升职
        $return['statistics']['demotion']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['demotion'] == '是';
        })->count();//降职
        $return['statistics']['stand_down']  = $statistics->filter(function($v){
            return $v['leave_post'] != '是' && $v['stand_down'] == '是';
        })->count();//待离岗
        $return['statistics']['leave_post']  = $statistics->filter(function($v){
            return $v['leave_post'] == '是';
        })->count();//已离岗

//        $return['statistics']['full_time']  = model('CompanyStaffManage')->where(['job_nature'=>'全职'])->count();//全职
//        $return['statistics']['part_time']  = model('CompanyStaffManage')->where(['job_nature'=>'兼职'])->count();//兼职
//        $return['statistics']['intern']  = model('CompanyStaffManage')->where(['entry_status'=>'实习生'])->count();//实习生
//        $return['statistics']['trial_period']  = model('CompanyStaffManage')->where(['entry_status'=>'试用期'])->count();//试用期
//        $return['statistics']['later_officially']  = model('CompanyStaffManage')->where(['entry_status'=>'待转正'])->count();//待转正
//        $return['statistics']['transfer']  = model('CompanyStaffManage')->where(['transfer'=>'是'])->count();//调岗
//        $return['statistics']['promotion']  = model('CompanyStaffManage')->where(['promotion'=>'是'])->count();//升职
//        $return['statistics']['demotion']  = model('CompanyStaffManage')->where(['demotion'=>'是'])->count();//降职
//        $return['statistics']['stand_down']  = model('CompanyStaffManage')->where(['stand_down'=>'是'])->count();//待离岗
//        $return['statistics']['leave_post']  = model('CompanyStaffManage')->where(['leave_post'=>'是'])->count();//已离岗

        $return['items'] = $list;
        $this->ajaxReturn(200, '获取数据成功', $return);
    }

    public function import()
    {
        $extra = input('post.extra/s','','trim');
        $file = input('file.file');
        if (!$file) {
            $this->ajaxReturn(500, '请选择文件');
        }
        $this->ajaxReturn(200, '请选择文件',$file);

    }
    public function editInfo()
    {
        $this->interceptCompanyProfile();
        $id=input('get.id/d', 0, 'intval');
        if(!$id){
            $this->ajaxReturn(500, '缺少参数');
        }
        $CompanyStaffManage = model('CompanyStaffManage')
            ->alias('cs')
            ->field('*')
            ->where(['id' =>$id])
            ->find();
        $this->ajaxReturn(200, '获取成功',$CompanyStaffManage);
    }
    public function save()
    {
        $id=input('post.id/d', 0, 'intval');
        $departments = input('post.department/a', []);
        $companys = input('post.company/a', []);
        $input = [
            'com_id' => $this->company_profile->id,
            'name' => input('post.name/s', null, 'trim,badword_filter'),
            'age' => input('post.age/s', null, 'trim,badword_filter'),
            'contract_duration' => input('post.contract_duration/s', null, 'trim,badword_filter'),
            'core_talent' => input('post.core_talent/s', null, 'trim,badword_filter'),
            'education' => input('post.education/s', null, 'trim,badword_filter'),
            'efficient_staff' => input('post.efficient_staff/s', null, 'trim,badword_filter'),
            'entry_status' => input('post.entry_status/s', null, 'trim,badword_filter'),
            'entry_time' => input('post.entry_time/s', date('Y-m-d'), 'trim,badword_filter'),
            'experience' => input('post.experience/s', null, 'trim,badword_filter'),
            'gender' => input('post.gender/s', null, 'trim,badword_filter'),
            'job_nature' => input('post.job_nature/s', null, 'trim,badword_filter'),
            'mailbox' => input('post.mailbox/s', null, 'trim,badword_filter'),
            'mobile' => input('post.mobile/s', null, 'trim,badword_filter'),
            'postname' => input('post.postname/s', null, 'trim,badword_filter'),
            'recruit_team' => input('post.recruit_team/s', null, 'trim,badword_filter'),
            'replacement_plan' => input('post.replacement_plan/s', null, 'trim,badword_filter'),

            'social_security' => input('post.social_security/s', null, 'trim,badword_filter'),
            'trial_period' => input('post.trial_period/s', null, 'trim,badword_filter'),
            'coms_id' => implode(',',array_filter($companys)),
            'coms_d_id' => implode(',',array_filter($departments)),
        ];
        $input['entry_time'] || $input['entry_time'] = date('Y-m-d');
        $resignation_time = input('post.resignation_time/s', null, 'trim,badword_filter');
        if($resignation_time){
            $input['resignation_time'] = $resignation_time;
        }
        $uid = 0;
        Db::startTrans();
        try{
            if($id){
                $uid = model('CompanyStaffManage')->where('id',$id)->value('uid');
                // 创建员工账号
                $input['uid'] = model('Member')->editStaff(['company_id'=>$this->company_profile->id,'uid'=>$uid,'mobile'=>$input['mobile'],'status'=>$input['recruit_team']=='是'?1:0]);
                $result = model('CompanyStaffManage')
                    ->allowField(true)
                    ->save($input, [
                        'id' => $id
                    ]);

            }else{
                // 更新员工账号
                $input['uid'] = model(Member::class)->editStaff(['company_id'=>$this->company_profile->id,'uid'=>$uid,'mobile'=>$input['mobile'],'status'=>$input['recruit_team']=='是'?1:0]);
                $result = model('CompanyStaffManage')
                    ->allowField(true)
                    ->save($input);
                if($result){

                    //计算编制人数
                    $coms_id = explode(',',$input['coms_d_id']);
                    $coms_d_id = explode(',',$input['coms_d_id']);
                    $pid = end($coms_d_id)?end($coms_d_id):end($coms_id);
                    (new Structure())->makeCompanyCurrentNum($pid,1);

                    $id = model('CompanyStaffManage')->id;
                }
            }
            Db::commit();
            $this->ajaxReturn(200, '保存成功', [
                'id' => $id,
                'result' => $result,
            ]);
        }catch (Exception $e){
            Db::rollback();
            dolog(__METHOD__.'Error',[$e->getMessage(),$e->getLine(),$e->getFile()]);
            return $this->returnJson(500,'系统错误');
        }


    }

    public function option(){
        $id=input('post.id/d');
        $key=input('post.key/s', '', 'trim,badword_filter');
        if(empty($id))
        {
            $this->ajaxReturn(500, '缺少参数',$id);
        }
        $leave_post = CompanyStaffManage::where('id',$id)->value('leave_post');
        if($leave_post == '是'){
            return $this->returnJson(500,'该员工已离职');
        }
        $fields = ['leave_post','stand_down','demotion','promotion','transfer'];
        if(!in_array($key,$fields)){
            return $this->returnJson('500','key参数错误');
        }
        foreach ($fields as $field){
            $data[$field] = null;
            $data[$key] = '是';
            if($key == 'leave_post'){
                $data['resignation_time'] = date('Y-m-d');
            }
        }
        !empty($data) && $result = model('CompanyStaffManage')
            ->allowField(true)
            ->save($data, [
                'id' =>$id
            ]);
        $this->ajaxReturn(200, '操作成功');
    }

    public function optionBatch(){
        $ids=input('post.ids/a');
        $key=input('post.key/s', '', 'trim,badword_filter');
        if(empty($ids))
        {
            $this->ajaxReturn(500, '缺少参数',$ids);
        }
        $fields = ['leave_post','stand_down','demotion','promotion','transfer'];
        if(!in_array($key,$fields)){
            return $this->returnJson('500','key参数错误');
        }
        $valid_ids = CompanyStaffManage::whereIn('id',$ids)->where('leave_post',null)->column('id');
        foreach ($fields as $field){
            $data[$field] = null;
            $data[$key] = '是';
            if($key == 'leave_post'){
                $data['resignation_time'] = date('Y-m-d');
            }
        }
        !empty($data) && $result = model('CompanyStaffManage')
            ->allowField(true)
            ->save($data, [
                'id' =>array('in',$valid_ids)
            ]);
        $this->ajaxReturn(200, '操作成功');
    }



    public function delBatch(){
        $ids=input('post.ids/a');
        if(empty($ids))
        {
            $this->ajaxReturn(500, '缺少参数');
        }
        foreach ($ids as $id)
        {
            $this->del($id,false);
        }
        $this->ajaxReturn(200, '删除成功');
    }

    public function del($id = null,$isReturn=true)
    {
        $id=$id ? $id : input('post.id/d', 0, 'intval');
        if(!$id){
            return !$isReturn?false: $this->ajaxReturn(500, '缺少参数');
        }
        \think\Db::startTrans();
        try {
            $CompanyStaffManage =model('CompanyStaffManage')->where(['id'=> $id])->find();
            $coms_id = explode(',',$CompanyStaffManage->coms_id);
            $coms_d_id = explode(',',$CompanyStaffManage->coms_d_id);
            $pid = end($coms_d_id)?end($coms_d_id):end($coms_id);
            (new Structure())->makeCompanyCurrentNum($pid,-1);
            $CompanyStaffManage->delete();
            \think\Db::commit();
        } catch (\Exception $e) {
            \think\Db::rollBack();
            return !$isReturn? false: $this->ajaxReturn(500, $e->getMessage());
        }
        return !$isReturn? true: $this->ajaxReturn(200, '删除成功');

    }
    public function downloadStaffTpl() {
        $url = config('global_config.sitedomain') . DS . 'upload/resource/import_staff_tpl.xlsx';
        $this->ajaxReturn(200, '', $url);
    }
    /**
     * 上传员工
     * @return void
     */
    public function upload() {
        $file = input('file.file');
        if (!$file) {
            $this->ajaxReturn(500, '请选择文件');
        }
        $config = ['fileupload_ext' => 'docx,pdf,xlsx,', 'uploadfile_dir' => 'resume'];
        $filemanager = new \app\common\lib\FileManager($config);
        $res = $filemanager->uploadReturnPath($file);
        if (false !== $res) {
            $file = SYS_UPLOAD_PATH . $res['save_path'];
            $dataList = StaffParseLogic::fileParse($file);
            if (empty($dataList)) {
                unlink($file);
                $this->ajaxReturn(500, '解析失败');
            }
            $res = StaffLogic::import($dataList, $this->company_profile);
            if (empty($res)) {
                $this->ajaxReturn(500, '导入失败');
            }
            $this->ajaxReturn(200, '导入成功', $res);
        } else {
            $this->ajaxReturn(500, $filemanager->getError());
        }
    }

    public static function regAutoRecruit($com_id){
        // todo HR注册成为面试官
    }

}